package com.alibaba.shopping_seckill_customer_api.controller;

import com.alibaba.shopping_common.pojo.Orders;
import com.alibaba.shopping_common.pojo.SeckillGoods;
import com.alibaba.shopping_common.result.BaseResult;
import com.alibaba.shopping_common.service.OrderService;
import com.alibaba.shopping_common.service.SeckillService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName SeckiilGoodsController
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/20 16:38
 */
@RestController
@RequestMapping("/user/seckillGoods/")
public class SeckillGoodsController {

    @DubboReference
    private SeckillService seckillService;

    @DubboReference
    private OrderService orderService;

    /**
     * 从Redis中分页查询正在售卖的秒杀商品
     * @param page 页码
     * @param size 页面大小
     * @return
     */
    @GetMapping("/findByPage")
    public BaseResult<Page<SeckillGoods>>findByPage(int page,int size){
        Page<SeckillGoods> pageByRedis = seckillService.findPageByRedis(page, size);
        return BaseResult.OK(pageByRedis);
    }

    @GetMapping("/findById")
    public BaseResult<SeckillGoods>findById(Long id){
        SeckillGoods seckillGoodsByRedis = seckillService.findSeckillGoodsByRedis(id);
        seckillGoodsByRedis = null;
        // 从Redis中查询秒杀商品
        if (seckillGoodsByRedis != null){
            return BaseResult.OK(seckillGoodsByRedis);
        }else {
            // 从MySQL中查询秒杀商品
            SeckillGoods seckillGoodsByMySql = seckillService.findSeckillGoodsByMySql(id);
            return BaseResult.OK(seckillGoodsByMySql);
        }
    }

    /**
     * 生成秒杀订单
     * @param orders
     * @param userId
     * @return
     */
    @PostMapping("/add")
    public BaseResult<Orders> add(@RequestBody Orders orders,@RequestParam(name = "userId",
            required = false, defaultValue = "29") Long userId){
        // 将用户ID回填到订单对象中
        orders.setUserId(userId);
        // 创建订单
        Orders order = seckillService.createOrder(orders);
        return BaseResult.OK(order);
    }

    /**
     * 根据ID查询秒杀订单详情
     * @param id
     * @return
     */
    @GetMapping("/findOrder")
    public BaseResult<Orders>findOrder(String id){
        Orders orders = seckillService.findOrders(id);
        return BaseResult.OK(orders);
    }

    @GetMapping("/pay")
    public BaseResult<Orders>pay(String id){
        // 支付秒杀订单
        Orders orders = seckillService.pay(id);
        // 将数据存入数据库
        orderService.buildOrder(orders);
        return BaseResult.OK(orders);
    }
}




